package com.lngsyz.ywtb.biz.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lngsyz.ywtb.entity.LoginInfo;
import com.lngsyz.ywtb.entity.hx.AcceptHx;
import com.lngsyz.ywtb.entity.hx.AddHxElecOrder;
import com.lngsyz.ywtb.entity.hx.AddHxElecOrderInnerSeal;
import com.lngsyz.ywtb.entity.hx.AddHxPhyOrder;
import com.lngsyz.ywtb.entity.hx.AddHxPhyOrderInnerSeal;
import com.lngsyz.ywtb.entity.hx.GetHxList;
import com.lngsyz.ywtb.entity.hx.OutHxList;
import com.lngsyz.ywtb.entity.source1.SImg;
import com.lngsyz.ywtb.entity.source1.SPermit;
import com.lngsyz.ywtb.entity.source1.SSeal;
import com.lngsyz.ywtb.entity.source1.SystemCompany;
import com.lngsyz.ywtb.entity.source1.SystemFileupload;
import com.lngsyz.ywtb.entity.source1.YwtbCityApp;
import com.lngsyz.ywtb.enumeration.Beiancailiao;
import com.lngsyz.ywtb.enumeration.SealMedia;
import com.lngsyz.ywtb.pay.exception.RequestSystemException;
import com.lngsyz.ywtb.util.CommonUtil;
import com.lngsyz.ywtb.util.jwt.TokenUtil;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

@Service
public class HxService {
    
	@Autowired
	YwtbCityAppService ywtbCityAppService;
	@Autowired
	GsYwtbService gsYwtbService;
	@Autowired
	SystemFileuploadService systemFileuploadService;
	@Autowired
	SystemCompanyService systemCompanyService;
	@Autowired
	SystemCustomService systemCustomService;
	@Autowired
	SImgService sImgService;
	@Autowired
	SPermitService sPermitService;
	@Autowired
	SSealService sSealService;
	
	public Map<String, String> COMPANY_USERID_MAP;

	/**
	 * 获取token
	 * @param appId
	 * @param appSecret
	 * @return
	 */
    public String getToken(String appId, String appSecret, String userId) throws Exception {
    	YwtbCityApp yca = ywtbCityAppService.findByAppId(appId);
    	if(yca != null) {
    		if(StringUtils.equals(appSecret, yca.getSecret())) {
    			// TODO
    			// package LoginInfo
    			LoginInfo loginInfo = new LoginInfo();
    			loginInfo.setAppId(appId);
    			loginInfo.setDistrictCity(yca.getDistrictCity());
    			loginInfo.setUserId(userId);
    			// create jwt token
    			String token = TokenUtil.generateToken(loginInfo);
    			return token;
    		} else {
    			throw new RequestSystemException("授权信息有误");
    		}
    	} else {
    		throw new RequestSystemException("授权信息有误");
    	}
    }
    
    /**
     * 添加物理订单
     * @return
     */
    public void addPhyOrder(AddHxPhyOrder addHxPhyOrder, LoginInfo loginInfo) throws Exception {
    	// 保存批单信息
    	SPermit sp = packageSPermit(addHxPhyOrder, loginInfo);
    	sPermitService.insert(sp);
    	String permitId = sp.getId();
    	// 保存印章信息
    	List<SSeal> sss = packagePhySSeal(addHxPhyOrder.getSeals(), permitId, loginInfo);
    	sSealService.inserts(sss);
    	// 保存图片信息
    	String district = addHxPhyOrder.getDistrict();
    	dealImage(district, addHxPhyOrder.getCrpImgFront(), Beiancailiao.TYPE_01.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getCrpImgBack(), Beiancailiao.TYPE_02.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrFace(), Beiancailiao.TYPE_10.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrImgFront(), Beiancailiao.TYPE_03.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrImgBack(), Beiancailiao.TYPE_04.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getYyzz(), Beiancailiao.TYPE_05.getKey(), permitId);
    }
    
    private SPermit packageSPermit(AddHxPhyOrder addHxPhyOrder, LoginInfo loginInfo) {
    	SPermit sp = new SPermit();
    	sp.setId(CommonUtil.createUuid());
    	sp.setDistrict(addHxPhyOrder.getDistrict());
    	sp.setCustomId(addHxPhyOrder.getCustomId());
    	sp.setCustomName(addHxPhyOrder.getCustomName());
    	sp.setCustomInstCode(addHxPhyOrder.getCustomInstCode());
    	sp.setCompanyId("");
    	sp.setPermitApplyName(addHxPhyOrder.getApplyName());
    	sp.setPermitApplyCertNo(addHxPhyOrder.getApplyCertNo());
    	sp.setPermitApplyPhone(addHxPhyOrder.getApplyPhone());
    	sp.setAccept("0"); //承接状态（0：未承接 1：已承接）
    	sp.setUserId(loginInfo.getUserId());
    	return sp;
    }
    
    private List<SSeal> packagePhySSeal(List<AddHxPhyOrderInnerSeal> seals, String permitId, LoginInfo loginInfo){
    	List<SSeal> rtn = new ArrayList<SSeal>();
    	for(AddHxPhyOrderInnerSeal seal : seals) {
    		SSeal ss = new SSeal();
    		ss.setId(CommonUtil.createUuid());
    		ss.setSealType(seal.getSealType());
    		ss.setCount(seal.getCount());
    		ss.setSPermitId(permitId);
    		ss.setSealMedia(SealMedia.PHYSICAL.getKey());
//    		ss.setReferSealCode(referSealCode);
    		ss.setUserId(loginInfo.getUserId());
    		rtn.add(ss);
    	}
    	return rtn;
    }
    
    private String dealImage(String district, MultipartFile file, String imgType, String permitId) throws Exception {
    	if(file != null) {
    		if(StringUtils.isBlank(district)) {
    			district = "2100";
    		}
    		String fileName = file.getOriginalFilename();
    		SystemFileupload sf = systemFileuploadService.packageSystemFileupload(district, fileName);
    		systemFileuploadService.insert(sf);
    		CommonUtil.saveFile(file, sf.getFilepath());
    		
    		SImg si = new SImg();
    		si.setId(CommonUtil.createUuid());
    		si.setImgType(imgType);
    		si.setImgId(sf.getId());
    		si.setSPermitId(permitId);
    		sImgService.insert(si);
    		return sf.getId();
    	} else {
    		return null;
    	}
    }
    
    /**
     * 添加电子订单
     * @return
     */
    public void addElecOrder(AddHxElecOrder addHxElecOrder, LoginInfo loginInfo) throws Exception {
    	// 保存批单信息
    	SPermit sp = packageSPermit(addHxElecOrder, loginInfo);
    	sPermitService.insert(sp);
    	String permitId = sp.getId();
    	// 保存印章信息
    	List<SSeal> sss = packageElecSSeal(addHxElecOrder.getSeals(), permitId, loginInfo);
    	sSealService.inserts(sss);
    	// 保存图片信息
    	String district = addHxElecOrder.getDistrict();
    	dealImage(district, addHxElecOrder.getCrpImgFront(), Beiancailiao.TYPE_01.getKey(), permitId);
    	dealImage(district, addHxElecOrder.getCrpImgBack(), Beiancailiao.TYPE_02.getKey(), permitId);
    	dealImage(district, addHxElecOrder.getJbrFace(), Beiancailiao.TYPE_10.getKey(), permitId);
    	dealImage(district, addHxElecOrder.getJbrImgFront(), Beiancailiao.TYPE_03.getKey(), permitId);
    	dealImage(district, addHxElecOrder.getJbrImgBack(), Beiancailiao.TYPE_04.getKey(), permitId);
    	dealImage(district, addHxElecOrder.getYyzz(), Beiancailiao.TYPE_05.getKey(), permitId);
    }
    

    private SPermit packageSPermit(AddHxElecOrder addHxElecOrder, LoginInfo loginInfo) {
    	SPermit sp = new SPermit();
    	sp.setId(CommonUtil.createUuid());
    	sp.setDistrict(addHxElecOrder.getDistrict());
    	sp.setCustomId(addHxElecOrder.getCustomId());
    	sp.setCustomName(addHxElecOrder.getCustomName());
    	sp.setCustomInstCode(addHxElecOrder.getCustomInstCode());
    	sp.setCompanyId("");
    	sp.setPermitApplyName(addHxElecOrder.getApplyName());
    	sp.setPermitApplyCertNo(addHxElecOrder.getApplyCertNo());
    	sp.setPermitApplyPhone(addHxElecOrder.getApplyPhone());
    	sp.setAccept("0"); //承接状态（0：未承接 1：已承接）
    	sp.setUserId(loginInfo.getUserId());
    	return sp;
    }
    
    private List<SSeal> packageElecSSeal(List<AddHxElecOrderInnerSeal> seals, String permitId, LoginInfo loginInfo){
    	List<SSeal> rtn = new ArrayList<SSeal>();
    	for(AddHxElecOrderInnerSeal seal : seals) {
    		SSeal ss = new SSeal();
    		ss.setId(CommonUtil.createUuid());
    		ss.setSealType(seal.getSealType());
    		ss.setCount(1);
    		ss.setSPermitId(permitId);
    		ss.setSealMedia(SealMedia.PHYSICAL.getKey());
    		ss.setReferSealCode(seal.getReferSealCode());
    		ss.setUserId(loginInfo.getUserId());
    		rtn.add(ss);
    	}
    	return rtn;
    }
    
    public List<OutHxList> getList(GetHxList getHxList, int page, int size){
    	List<SPermit> sPermits = sPermitService.findList(getHxList, page, size);
    	List<OutHxList> rtn = new ArrayList<OutHxList>();
    	for(SPermit sp : sPermits) {
    		OutHxList ol = new OutHxList();
    		ol.setCustomName(sp.getCustomName());
    		ol.setCustomInstCode(sp.getCustomInstCode());
    		ol.setApplyName(sp.getPermitApplyName());
    		ol.setApplyCertNo(sp.getPermitApplyCertNo());
    		ol.setApplyPhone(sp.getPermitApplyPhone());
    		ol.setAccept(sp.getAccept());
    		rtn.add(ol);
    	}
    	return rtn;
    }
    
    public int getCount(GetHxList getHxList) {
    	return sPermitService.findTotal(getHxList);
    }
    
    /**
     * 承接
     * @return
     */
    public void accept(AcceptHx acceptHx, LoginInfo loginInfo) throws Exception {
    	// 取申请内容
    	String id = acceptHx.getId();
    	SPermit sPermit = sPermitService.findById(id);
    	if(sPermit != null) {
    		String companyInstCode = acceptHx.getInstCode();
    		SystemCompany sc = systemCompanyService.findByInstCode(companyInstCode);
    		if(sc != null) {
    			if(StringUtils.isBlank(sPermit.getCompanyId()) || StringUtils.equals(sc.getId(), sPermit.getCompanyId())) {
    				// 查询system_custom，找到customId
    				String customId = sPermit.getCustomId();
					// 查询system_company，找到companyId
					
					// 查询system_user,找到userId
					
					// 创建承接单，取得permitId
					
					// 补充system_seal
					
					// 补充system_fileupload
					
					// 备案
    			} else {
    				throw new RequestSystemException("订单指定刻章厂与当前刻章厂不一致");
    			}
    		} else {
    			throw new RequestSystemException("订单指派刻章厂不存在，需要修改");
    		}
    	} else {
    		throw new RequestSystemException("未找到当前订单");
    	}
    	
    	
    	
    	// 保存批单信息
    	SPermit sp = packageSPermit(addHxPhyOrder, loginInfo);
    	sPermitService.insert(sp);
    	String permitId = sp.getId();
    	// 保存印章信息
    	List<SSeal> sss = packagePhySSeal(addHxPhyOrder.getSeals(), permitId, loginInfo);
    	sSealService.inserts(sss);
    	// 保存图片信息
    	String district = addHxPhyOrder.getDistrict();
    	dealImage(district, addHxPhyOrder.getCrpImgFront(), Beiancailiao.TYPE_01.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getCrpImgBack(), Beiancailiao.TYPE_02.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrFace(), Beiancailiao.TYPE_10.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrImgFront(), Beiancailiao.TYPE_03.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getJbrImgBack(), Beiancailiao.TYPE_04.getKey(), permitId);
    	dealImage(district, addHxPhyOrder.getYyzz(), Beiancailiao.TYPE_05.getKey(), permitId);
    }
    

    private Map<String, String> companyUserId() {
    	if(COMPANY_USERID_MAP == null) {
    		COMPANY_USERID_MAP = new HashMap<String, String>();
    		// 朝阳天隆
    		COMPANY_USERID_MAP.put("", "");
    		// 沈阳特安瑞
    		COMPANY_USERID_MAP.put("", "");
    		// 大连昊泰
    		COMPANY_USERID_MAP.put("", "");
    	}
    	return COMPANY_USERID_MAP;
    }
}
